<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Common;

use App\Exceptions\ApiException;
use Flc\Dysms\Client;
use Flc\Dysms\Request\SendSms;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Tool
{

    public static $request;

    public static function jsonHandle($data = [], $code = 0, $desc = '')
    {
        $arr = ['ret' => $code, 'desc' => $desc];
        if ($data) {
            $arr['data'] = $data;
        }
        $response = preg_replace_callback("#\\\u([0-9a-f]{4})#i", function ($m) {
            return iconv('UCS-2BE', 'UTF-8', pack('H4', $m[1]));
        }, json_encode($arr));
        Logger::instance()->info(self::getUri(), "RESPONSE:  $response");
        return $response;
    }

    /**
     * 获取当前请求的路由名
     * @return mixed
     */
    public static function getUri()
    {
        return self::$request->route()->uri;
    }


    /**
     * 返回Redis中的随机数
     * @return mixed
     * @throws ApiException
     */
    public static function redisRand()
    {
        $pwd = Redis::spop('Q_' . env('REDIS_ROOM_KEY'));
        if (empty($pwd)) {
            Tool::sendErrorSms();
            throw new ApiException('随机房间号为空');
        }
        return $pwd;
    }


    public static function setRedisRoomKey($room_id, $pwd)
    {
        $path = file_get_contents(base_path() . '/redisscript/create_room.lua');
        return Redis::eval($path, 3, env('REDIS_ROOM_KEY'), $room_id, $pwd);
    }


    public static function redisInit()
    {
        return Redis::eval(file_get_contents(base_path() . '/redisscript/init.lua'), 1, env('REDIS_ROOM_KEY'));
    }


    public static function getRedisRoomId($rand_password)
    {
        return Redis::eval(file_get_contents(base_path() . '/redisscript/get_room.lua'), 2, env('REDIS_ROOM_KEY'), $rand_password);
    }

    public static function sendErrorSms()
    {
        $client = new Client([
            'accessKeyId' => 'LTAIJ3BjxcM6d3Pm',
            'accessKeySecret' => 'FCeLpv64JTLogoIuwJSLiQy4FGENCy',
        ]);
        $sms    = new SendSms();
        $sms->setPhoneNumbers([15626104771,18813987119]);
        $sms->setSignName('贵州智星无限科技有限公司');
        $sms->setTemplateCode('SMS_130921434');
        $sms->setTemplateParam(['serverid' => str_replace('.', '', $_SERVER['SERVER_ADDR']), 'level' => 3, 'reason' => 'redis随机数集合数据为空']);
        $client->execute($sms);
    }


    /**
     * 返回毫秒
     * @return float
     */
    public static function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    }


    /**
     * 咪咕签名
     * @param $body
     * @return string
     */
    public static function miGuSignature($body)
    {
        $str = "timestamp=" . (string)$body['timestamp'];
        foreach ($body as $key => $value) {
            if ($key != 'timestamp') {
                $str = $str . "&" . $key . "=" . $value;
            }
        }
        return strtoupper(md5($str));
    }


    /**
     * @param $uid
     * @return mixed | integer
     * @throws ApiException
     */
    public static function getMiGuId($uid)
    {
        $migu_id = DB::table('t_player_info')->where('id', $uid)->value('migu_id');
        if (!$migu_id) {
            throw new ApiException('咪咕ID不存在,调用咪咕接口需要用户与该ID绑定');
        }
        return $migu_id;
    }

}